package com.itany.cloud.config;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient;
import org.springframework.cloud.loadbalancer.core.RandomLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration
@LoadBalancerClient(value = "cloud-nacos-provider",configuration = CustomLoadBalancerConfiguration.class)
public class CustomLoadBalancerConfiguration {

    /**
     * 返回ReactorLoadBalancer接口提供的实现类,不同的实现类表示的是不同的负载均衡策略
     * @param environment
     * @param loadBalancerClientFactory
     * @return 根据返回值不同,表示使用不同的负载均衡策略
     * RoundRobinLoadBalancer:默认值,轮询负载均衡
     * RandomLoadBalancer:随机负载均衡
     */
    @Bean
    ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment environment,
                                                            LoadBalancerClientFactory loadBalancerClientFactory) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        return new RandomLoadBalancer(loadBalancerClientFactory
                .getLazyProvider(name, ServiceInstanceListSupplier.class),
                name);
    }
}
